<template>
  <el-row :gutter="20">
    <el-card
      class="box-construction"
      shadow="always"
      :style="`height:${Height}px`"
    >
      <div class="box-title box-title-position">
        <div>绩效考核</div>
        <div class="add-btn">
          <el-date-picker
            v-model="monthDate"
            type="month"
            placeholder="选择月"
            value-format="yyyy-MM"
            @change="searchDate"
          />
        </div>
      </div>
      <el-col :span="4" style="margin-top: 30px; overflow: auto">
        <!-- default-expand-all -->
        <el-tree
          empty-text="暂无数据"
          ref="asyncTree"
          check-strictly
          :data="treeData"
          highlight-current
          :expand-on-click-node="false"
          :default-expanded-keys="defaultExpandId"
          node-key="id"
          :props="treeDefaultProps.defaultProps"
          :load="loadNode"
          lazy
          @node-click="handleNodeClick"
          :style="`width: 100%;min-height:60px;max-height:${
            Height - 85
          }px;overflow: auto;border: 1px solid #eee;`"
        >
          <div class="custom-tree-node" slot-scope="{ node }">
            <span>{{ node.label }}</span>
          </div>
        </el-tree>
      </el-col>
      <el-col :span="20">
        <div
          class="right-box"
          v-loading="leftLoading"
          :style="`max-height:${Height - 90}px;`"
        >
          <el-tabs
            v-if="leftData.length > 0"
            v-model="activeTab"
            @tab-click="handleClick"
          >
            <!-- 在名字上面添加消息提示数 -->
            <!-- <el-tab-pane
              v-for="(tab, index) in leftData"
              :name="String(tab.id)"
              :label="tab.name"
              :key="tab.id"
            >
              <span slot="label">
                <el-badge
                  :value="pointData[index] ? pointData[index] : '...'"
                  style="top: 10px; right: 0px; height: 45px; line-height: 35px"
                  >{{ tab.name }}</el-badge
                >
              </span> -->
            <el-tab-pane
              v-for="tab in leftData"
              :name="String(tab.id)"
              :label="tab.name"
              :key="tab.id"
            >
              <el-table
                highlight-current-row
                border
                show-summary
                :summary-method="getTotal"
                v-loading="rightLoading"
                :show-header="false"
                :data="rightData"
                :max-height="`${Height - 165}`"
                style="width: 100%; margin-top: 5px"
              >
                <el-table-column
                  prop="month"
                  label="时间"
                  width="75"
                ></el-table-column>
                <el-table-column prop="name" label="考勤内容">
                  <template slot-scope="scope" sortable>
                    <div
                      style="cursor: pointer"
                      @click="getPerScore(scope.row)"
                    >
                      <span class="html-content" v-html="scope.row.name"></span>
                      <!-- {{ scope.row.name | filterAdd1 }} -->
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="score" label="职位" width="120">
                  <template slot-scope="scope" sortable>
                    <!-- <el-input-number
                      autofocus
                      v-model="scope.row.score"
                      :precision="2"
                      :step="0.01"
                      size="mini"
                      style="width: 100%"
                      @focus="pwdChange1(scope.row, scope.$index)"
                      @blur="pwdChange2(scope.row, scope.$index)"
                    ></el-input-number> -->
                    <el-input
                      autofocus
                      v-model="scope.row.score"
                      oninput="value=value.replace(/[^\-?\d.]/g,'').replace(/^\./g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.').replace('-','$#$').replace(/\-/g,'').replace('$#$','-').slice(0,value.indexOf('.')+3)"
                      size="mini"
                      style="width: 70%"
                      :disabled="scope.row.locked"
                      @focus="pwdChange1(scope.row, scope.$index)"
                      @blur="pwdChange2(scope.row, scope.$index)"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="mark" label="备注" width="150">
                  <template slot-scope="scope">
                    <el-input
                      type="textarea"
                      size="mini"
                      :autosize="{ minRows: 1.5 }"
                      placeholder="请输入备注"
                      v-model="scope.row.mark"
                      :disabled="scope.row.locked"
                      @blur="pwdChange2(scope.row, scope.$index)"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
          <div class="no-data" v-else>暂无数据</div>
        </div>
      </el-col>
    </el-card>
    <EditForm
      ref="editForm"
      :title="formTitle"
      :datas.sync="editRow"
      :visible.sync="visible"
    />
  </el-row>
</template>
<script>
import orgAPI from "@apis/organize";
import perAPI from "@apis/performance";
import { mapState } from "vuex";
import EditForm from "./editForm/index";
export default {
  data() {
    return {
      uid: "",
      monthDate: "", //时间筛选

      orgid: "", //获取右边数据所需要的部门id

      treeDefaultProps: {
        defaultProps: {
          children: "children",
          label: "label",
        },
        defaultExpanded: [1],
      },

      leftLoading: false,
      rightLoading: false,
      selectRow: null,
      leftData: [],
      pointData: [],
      cueLeftRow: {},
      rightData: [],
      data: [],
      treeData: [],
      defaultExpandId: [],
      visible: false,
      formTitle: "参与项目绩效详情",
      editRow: {},
      searchScores: false, //标注是否type=1或者type=2已经请求过数据

      activeTab: "",
    };
  },
  filters: {
    filterAdd1(item) {
      return item.replace(/&amp;lt;/g, "≤");
    },
  },
  components: {
    EditForm,
  },
  computed: {
    ...mapState({
      userInfo: "auth",
    }),
    Height() {
      return document.documentElement.clientHeight - 110;
    },
  },
  created() {
    let date = new Date();
    let Year = date.getFullYear();
    let Day =
      date.getMonth() + 1 < 10
        ? `0${date.getMonth() + 1}`
        : date.getMonth() + 1;
    this.monthDate = `${Year}-${Day}`;
    this.uid = this.userInfo.user.review_id;
    this.getLeftList();
  },
  mounted() {},
  methods: {
    getTotal(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        //区分 质量和日常
        const normal = data.filter((i) => i.class_id == 1);
        const quality = data.filter((i) => i.class_id == 2);
        const sum_normal = this.sum(normal.map((i) => Number(i.score)));
        let dataArr = JSON.parse(JSON.stringify(quality));
        const special = dataArr.filter((item) => {
          if (item.spot_id === 92 || item.spot_id === 206) return item;
        });
        if (special.length > 1) {
          let max = undefined;
          special.map((i) => {
            if (max) {
              if (i.score > max.score) {
                max = i;
              }
            } else {
              max = i;
            }
          });
          dataArr.map((item) => {
            if (item.spot_id === 92 || item.spot_id === 206) {
              if (item.id !== max.id) {
                item.score = 0;
              }
            }
          });
        }

        const values = dataArr
          .filter((item) => item.weight !== 100)
          .map((i) => Number(i["score"]));
        const valuesWeight = dataArr
          .filter((item) => item.weight === 100)
          .map((i) => Number(i["score"]));
        let sum = this.sum(values) * 0.3 + 30;
        let sumWeight = this.sum(valuesWeight);
        const sum_quality = sum + sumWeight;

        // const values = data.map((item) => Number(item[column.property]));
        if (column.property === "score") {
          // sums[index] = values.reduce((prev, curr) => {
          //   const value = Number(curr);
          //   if (!isNaN(value)) {
          //     return prev + curr;
          //   } else {
          //     return prev;
          //   }
          // }, 0);
          if (normal.length) {
            sums[index] = sum_normal.toFixed(2);
          } else if (quality.length) {
            sums[index] = sum_quality.toFixed(2);
          }
          // sums[index] = (sum_normal + sum_quality).toFixed(2)
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    //时间筛选函数
    async searchDate(value) {
      this.leftLoading = true;
      this.orgid = "";
      await this.getOrgList(0);
      this.treeData = this.data;
      this.defaultExpandId = this.data.length ? [this.data[0].id] : [""];
      this.getLeftList();
    },

    //树状图数据懒加载函数
    async loadNode(node, resolve) {
      if (node.level == 0) {
        await this.getOrgList(0);
        this.defaultExpandId = this.data.length ? [this.data[0].id] : [""];
        return resolve(this.data);
      } else {
        await this.getOrgList(node.data.id);
        return resolve(this.data);
      }
    },
    //获取树状图数据
    async getOrgList(val = 0) {
      this.data = [];
      // let parmars = {
      //   pid: val,
      //   pageNo: 1,
      //   pageSize: 1000,
      // };
      let parmars = {
        month: this.monthDate,
        uid: this.uid,
        pid: val,
        pageNo: 1,
        pageSize: 1000,
      };
      await orgAPI
        // .getOrgList(parmars)
        .getOrgListTj(parmars)
        .then((res) => {
          res.data.map((item) => {
            this.data.push({
              pid: item.pid,
              id: item.id,
              label: item.orgname ? item.orgname : "label" + item.id,
              children: [],
            });
          });
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    handleNodeClick(data, node, nodeSelf) {
      this.orgid = data.id; //添加人员所在组织ID orgid
      this.leftLoading = true;
      this.getLeftList();
    },

    //左边人员数据
    getLeftList() {
      if (!this.userInfo.user.review_id) {
        this.leftLoading = false;
        this.$message.warning("请先到考核关系处关联用户，关联后请刷新页面！");
        return;
      }
      perAPI
        .viewedList({
          uid: this.userInfo.user.id,
          month: this.monthDate,
          orgid: this.orgid,
        })
        .then((res) => {
          this.leftData = [...res];
          this.leftLoading = false;
          this.$nextTick(() => {
            if (this.leftData.length <= 0) {
              this.rightData = [];
              return;
            }
            this.activeTab = String(this.leftData[0].id);

            this.rightLoading = true;
            this.cueLeftRow = { ...this.leftData[0] };
            this.getRightList(this.leftData[0]);
          });
        })
        .catch((err) => {
          this.leftData = [];
          this.leftLoading = false;
          if (err.data.code) {
            console.log(err, "err");
            this.$message.error(err.message);
          }
        });
    },
    //右边考核数据
    getRightList(val) {
      perAPI
        .viewedFrom({
          uid: val.id,
          orgid: val.orgid,
          performance_id: this.userInfo.user.review_id,
          month: this.monthDate,
        })
        .then((res) => {
          let datas = [];
          if (res && res.length > 0) {
            res.map((item) => {
              datas.push({ isSet: false, pop: true, ...item });
            });
          }
          this.rightData = [...datas];
          this.rightLoading = false;
        })
        .catch((err) => {
          this.rightData = [];
          this.rightLoading = false;
          if (err.data.code) {
            console.log(err, "err");
            this.$message.error(err.message);
          }
        });
    },
    //点击tab 请求数据
    handleClick(tab, event) {
      this.pointData = [];
      this.cueLeftRow = this.leftData.filter((item) => {
        return item.id == tab.name;
      })[0];
      this.rightLoading = true;
      this.getRightList(this.cueLeftRow);
    },
    //提交修改后的score
    setScore(val, row) {
      this.searchScores = false;
      perAPI
        .setSpotScore({
          id: row.id,
          score: row.score,
          mark: row.mark,
        })
        .then((res) => {
          // console.log(res, "res");
        })
        .catch((err) => {
          row.score = this.selectRow.score;
          row.mark = this.selectRow.mark;

          this.rightLoading = false;
          this.$message.error(err.message);
          console.log(err, "err");
        });
    },
    //type==2
    searchProjectScore(row, curRow) {
      this.searchScores = true;
      perAPI
        .getProjectTeamersScore({ uid: row.uid, month: curRow.month })
        .then((res) => {
          this.rightData.map((item) => {
            if (item.id == curRow.id) {
              item.pop = false;
            }
          });
          this.rightLoading = false;
          this.editRow = { ...res };
          this.visible = true;
        })
        .catch((err) => {
          if (err.data.code) {
            console.log(err, "err");
            this.$message.error(err.message);
            return;
          }
          this.rightData.map((item) => {
            if (item.id == curRow.id) {
              item.pop = false;
            }
          });
          this.rightLoading = false;
          this.editRow = {
            data: [],
            total_score: "0",
          };
          this.visible = true;
        });
    },
    //focus
    pwdChange1(row, index) {
      this.selectRow = { ...row };
      if (row.type == 2 && !this.searchScores) {
        this.searchScores = false;
        if (row.pop) {
          this.rightLoading = true;
          this.searchProjectScore(this.cueLeftRow, row);
        }
        this.rightData.map((item) => {
          item.pop = true;
        });
      }
    },
    pwdChange2(row, index) {
      this.setScore(this.selectRow, row);
    },
    //添加小红点标记
    getPerScore(row) {
      this.pointData = [];
      this.leftData.map((item) => {
        this.pointData.push(row.id);
      });
      this.$children[0].$children[0].$forceUpdate();
      // console.log(row, "getPerScore");
      // console.log(this.leftData, "leftData");
    },
    sum(values) {
      let sums = 0;
      if (!values.every((value) => isNaN(value))) {
        sums = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
      } else {
        sums = 0;
      }
      return sums;
    },
  },
};
</script>
<style lang="scss" scoped>
.box-title-position {
  position: relative;
  .add-btn {
    position: absolute;
    left: 150px;
    top: -6px;
  }
}
.custom-tree-node {
  font-size: 14px;
}
.no-data {
  color: #909399;
  text-align: center;
  font-size: 14px;
  margin-top: 20px;
}
.right-box {
  min-height: 40px;
  margin-top: 30px;
  padding: 10px;
  border: 1px solid rgb(238, 238, 238);
}
</style>